from django.contrib.gis.db.models import GeometryField
from django.http import Http404, HttpResponse
from django.db.models import get_model
import simplejson
import libxml2
import RDF

def get_object(app_name, model_name, object_id):
	model = get_model(app_name, model_name)
	if not model:
		raise Http404("No such model %s.%s" % (app_name, model_name))
	try:
		obj = model._default_manager.get(pk = object_id)
	except model.DoesNotExist:
		raise Http404("No such object %s.%s(%s)" %
			      (app_name, model_name, object_id))
	return obj

def detail_json(request, app_name, model_name, object_id):
	obj = get_object(app_name, model_name, object_id)
	details = { "core" : {},
		    "attributes" : [],
		    "annotation" : [] }
	core = [ "id", "uri" ]
	for f in obj._meta.fields:
		label = unicode(f.verbose_name)
		value = getattr(obj, f.name)
		if value and not isinstance(f, GeometryField):
			value = unicode(value)
			if f.name in core:
				details["core"][f.name] = { 
					"label" : label,
					"value" : value
					}
			else:
				details["attributes"].append((label, value))

	if hasattr(obj, "about"):
		def node_str(n):
			if n.is_resource():
				return str(n.uri)
			if n.is_literal():
				return n.literal_value["string"]

		for s in obj.about():
			print s
			if s.object.is_resource():
				q = RDF.Statement(s.object, None, None)
				for r in obj._meta.rdf.model.find_statements(q):
					print r
					details["annotation"].append(map(node_str, (r.subject, r.predicate, r.object)))
			else:
					details["annotation"].append(map(node_str, (s.subject, s.predicate, s.object)))

	return HttpResponse(simplejson.dumps(details))

def detail_kml(request, app_name, model_name, object_id):
	obj = get_object(app_name, model_name, object_id)
	doc = libxml2.newDoc("1.0")
	kml = doc.newChild(None, "kml", None)
	kmlns = kml.newNs("http://earth.google.com/kml/2.0", None)
	kml.setNs(kmlns)
	root = kml.newChild(kmlns, "Document", None)
	mark = root.newChild(kmlns, "Placemark", None)
	mark.setProp("id", "%s" % obj.pk)
	mark.newChild(kmlns, "name", unicode(obj))
	for f in obj._meta.fields:
		if isinstance(f, GeometryField):
			geom = getattr(obj, f.name)
			kgeomdoc = libxml2.parseDoc(geom.kml)
			kgeom = kgeomdoc.children
			kgeom.unlinkNode()
			kgeomdoc.freeDoc()
			mark.addChild(kgeom)
			
	response = HttpResponse()
	response["Content-Type"] = "text/plain"
	response.write(doc.serialize("utf-8", True))
	doc.freeDoc()

	return response
